import cpt from "crypto";
import { customAlphabet } from "nanoid";

/**
 * 是否为开发模式
 * @returns {boolean}
 */
export function isDev(): boolean {
  return process.env.NODE_ENV === "development";
}

/**
 * md5摘要
 * @param data
 * @returns
 */
export function md5(data: string) {
  let hash = cpt.createHash("md5");
  return hash.update(data + data.length + "bhbd_data_analysis").digest("hex");
}

export function containsAny(str: string, charsToRemove: string[]): string {
  return charsToRemove.reduce((accumulator, charToRemove) => {
    // 使用正则表达式和全局标志来替换所有匹配的字符
    const regex = new RegExp(charToRemove, "g");
    return accumulator.replace(regex, "");
  }, str);
}

/**
 * 移除字符串中的子字符串(匹配)
 * @param str
 * @param substrings
 * @returns
 */
export function removeSubstrings(str: string, substrings: string[]): string {
  // 将字符串数组转换为正则表达式字符类
  const regexStr = `[${substrings.join("")}]`;
  // 创建正则表达式对象
  const regex = new RegExp(regexStr, "gu");
  // 使用replace方法去除字符串中的匹配项
  return str.replace(regex, "");
}
/**
 * 验证字符是否包含
 * @param str
 * @param chars
 * @returns
 */
export function verificationIncludes(str: string, chars: string[]): boolean {
  return chars.some(char => str.includes(char));
}
/**
 * 暂停
 */
export async function sleep(n: number) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true);
    }, n);
  });
}

/**
 * 获取动态表后缀随机字符串
 */
export function randTableNameSuffix() {
  const nanoid = customAlphabet("1234567890abcdefghijklmnopqrstuvwxyz", 10);
  return nanoid(6);
}

// 从证件号中提取生日信息
export function getBirthdayFromIdCard(idCard: string) {
  let yearStart: number, monthStart: number, dayStart: number;
  if (idCard.length === 18) {
    yearStart = 6;
    monthStart = 10;
    dayStart = 12;
  } else if (idCard.length === 15) {
    yearStart = 6;
    monthStart = 8;
    dayStart = 10;
    idCard = "19" + idCard;
  } else {
    return "";
  }

  const year = idCard.substring(yearStart, yearStart + 4);
  const month = idCard.substring(monthStart, monthStart + 2);
  const day = idCard.substring(dayStart, dayStart + 2);

  return `${year}-${month}-${day}`;
}
